'use strict';

import React, {
    Component,
    PropTypes
} from 'react';
import ReactDOM, {
    render
} from 'react-dom';
import {
    R_header_fixed
} from './common/index';
import {
    HttpService,
    Toast
} from '../Http';

import {
    imgOnError,
    goJxtFn
} from '../Tool';

import Link from './common/Link'
import imgCard from '../img/card.png'
import imgSheng from '../img/shengji.png'
import phone from '../img/more/phone.png'
import deletes from '../img/more/delete.png'
import shiming from '../img/more/shiming.png'
import pay from '../img/pay/pay.png'
import tianjia from '../img/tianjia.png'
import genghuan from '../img/genghuan.png'
import defaultHeadImg from '../img/icon/defaultHeadImg.png' //默认头像
//import jiebang from '../img/more/jiebang.png'
import guashi from '../img/more/guashi.png'
import guashi3 from '../img/more/guashi3.png'
import imgBaby from '../img/baby.png'
import scode from '../img/scode.png'
import scodeh from '../img/scode2.png'
import bangding from '../img/more/bangding.png'
import users from '../img/users.png'
import authen from '../img/more/authen.png'
import unauthen from '../img/more/unauthen.png'
import j from '../img/more/jiantou.png'
import header from '../img/login/header.jpg'
import footer from '../img/login/footer.jpg'
import Popup from './common/popup'
import tongzhi from '../img/jianhuchengyuan.png'
import anquan from '../img/anquan.png'


//more2
import imgadd from '../img/more2/add.png'
import imganquan from '../img/more2/anquan.png'
import imgpay from '../img/more2/pay.png'
import imgchange from '../img/more2/change.png'
import imgcode from '../img/more2/code.png'
import imgguashi from '../img/more2/guashi.png'
import imgguashi2 from '../img/more2/guashi2.png'
import imgjiebang from '../img/more2/jiebang.png'
import imgpackage from '../img/more2/package.png'
import imgbuy from '../img/more2/buy.png'
import imgphone from '../img/more2/phone.png'
import imgusers from '../img/more2/users.png'
import imgtime from '../img/more2/time.png'

export default class More extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);

        this.state = {
            info: {},
            admin: {},
            uimg: users,
            utel: localStorage.userphone,
            viewCode: 0,
            viewtime: 0
        };

        this.config = {
            isSure: false,
            isCancel: false,
            no: '取消',
            yes: '确定',
            yes_cb: () => {
                let type = this.config.type
                if (type == 'change') {
                    _hmt.push(['_trackEvent', 'page', 'more', '更换设备']);
                    this.context.router.push('/addDevice/0');
                    return;
                }
                if (type == 'guashi') {
                    _hmt.push(['_trackEvent', 'page', 'more', '设备挂失']);
                    this.deviceGuaShi();
                    return;
                }
                _hmt.push(['_trackEvent', 'page', 'more', '解绑设备']);
                if (!!this.state.info.isadmin) {
                    this.delDevice2()
                } else {
                    this.delDevice()
                }
            },
            no_cb: () => {
                this.setState({
                    admin: {
                        flag: false
                    }
                });
            }
        };
    }

    /**
     * 点击升级设备
     */
    shengJi() {
        localStorage.shengji = 1;
        //升级设备按钮--添加百度统计点击事件
        console.log('升级设备');
        _hmt.push(['_trackEvent', 'page', 'more', '升级设备']);
    }
    updateUser() {
        Toast.toast('请首页下载APP修改头像');
    }
    /**
     * map页面加载完后--加载百度统计点击事件
     * 缴费的统计事件在componentWillMount方法里面
     * 升级设备统计事件在shengJi()方法里面
     */
    componentDidMount() {
        //遍历页面按钮--添加百度统计点击事件
        document.querySelector('.adddevicelink').onclick = function() {
            console.log('添加设备');
            _hmt.push(['_trackEvent', 'page', 'more', '添加设备']);
        }
        document.querySelector('.buydevicelink').onclick = function() {
            console.log('购买设备');
            _hmt.push(['_trackEvent', 'page', 'more', '购买设备']);
        }
        var paybox = document.querySelector('.tgPayMoney');
        if (paybox)
            paybox.onclick = function() {
                _hmt.push(['_trackEvent', 'page', 'more', '缴费']);
            };
    }

    componentWillMount() {
        if (localStorage.appToken == undefined) {
            Toast.toast('请先登录！');
            this.context.router.push('/');
            return;
        }
        HttpService.query({
            url: '/app/user/getUserinfo',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid
                //weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10116) {
                    let uimg = this.state.uimg;
                    if (res.data.headimg)
                        uimg = '/media' + res.data.headimg
                    this.setState({
                        utel: res.data.telephone,
                        uimg
                    })
                    localStorage.userphone = res.data.telephone;
                }
            })
        });
        this.getBabyInfo();
    }
    //获取宝贝信息
    getBabyInfo() {
        HttpService.query({
            url: '/app/object/getBabyJxt',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid
                //weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10038') {
                    let viewtime = 0;
                    if (res.data.deviceType == 2 && res.data.loststatus != 1) {
                        if (localStorage.overtime == undefined) {
                            if ((new Date().getTime() - new Date(res.data.endtime).getTime()) / 24 / 60 / 60 / 1000 >= -30)
                                viewtime = 1
                        } else {
                            if (localStorage.overtime.indexOf(this.props.params.babyid) == -1) {
                                if ((new Date().getTime() - new Date(res.data.endtime).getTime()) / 24 / 60 / 60 / 1000 >= -30)
                                    viewtime = 1
                            }
                        }
                    }

                    this.setState({
                        viewtime,
                        info: {
                            url: 'http://qr.liantu.com/api.php?&w=200&text=' + res.data.mdtid + '',
                            mdtid: res.data.mdtid,
                            telephone: res.data.telephone,
                            endTime: res.data.endtime,
                            userid: res.data.userid,
                            isadmin: res.data.isadmin,
                            authstatus: res.data.authstatus,
                            loststatus: res.data.loststatus,
                            deviceType: res.data.deviceType,
                            babyid: res.data.babyid,
                            babyname: res.data.babyname,
                            teachertel: res.data.teachertel,
                            deviceid: res.data.deviceid,
                            tianyin: res.data.tianyin,
                            jxtBabyId: res.data.jxtBabyId
                        }
                    });
                    localStorage.schoolName = res.data.schoolname
                }
            })
        })
    }

    //基本设备提示操作
    deviceAdd() {
        if (this.state.info.isadmin) {
            localStorage.babyname = this.state.info.babyname
            localStorage.teachertel = this.state.info.teachertel
            this.context.router.push('/addDevice/1');
            return
        }
        this.setState({
            admin: {
                flag: true
            }
        });
        var b = {
            tip: '温馨提示',
            content: '非设备管理员无法绑定设备，请联系设备管理员',
            type: 'adddevice',
            newTop: null,
            no: '知道了',
            yes: null
        };
        this.config = Object.assign({}, this.config, b);
    }

    //设备挂失
    deviceGuaShiTip() {
        this.setState({
            admin: {
                flag: true
            }
        });
        let config = {};
        const {
            deviceType,
            loststatus
        } = this.state.info;
        if (!this.state.info.isadmin) {
            config = {
                tip: '温馨提示',
                content: `非设备管理员无法${loststatus?'解除挂失':'挂失设备'},请联系设备管理员`,
                newTop: null,
                no: '知道了',
                yes: null
            };
        } else {
            config = {
                tip: `是否要${loststatus?'解除':''}挂失${deviceType == 2 ? '学生证' : '考勤卡'}？`,
                content: loststatus ? '解除挂失后，以前使用的功能将恢复。' : `<p>挂失后，${deviceType == 2 ? '定位、通话、安全区域':'考勤'}功能将无法使用，如果找回${deviceType == 2 ? '学生证' : '考勤卡'}请及时解除挂失。挂失15天后(含挂失当日)，如果未解除挂失，系统将自动注销考勤卡，如需补卡请联系客服：<a href='tel:4008273366'>400-827-3366</a></p>
`,
                newTop: null,
                yes: loststatus ? '解除挂失' : '立即挂失',
                type: 'guashi'
            };
        }
        this.config = Object.assign({}, this.config, config);
    }
    deviceGuaShi() {
        let url = '/app/device/lostreport'
        if (this.state.info.loststatus == 1) {
            url = '/app/device/cancelostreport'
        }
        HttpService.query({
            url,
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                userid: localStorage.userid,
                devicetype: this.state.info.deviceType,
                weixinclient: 'true'
            },
            success: (res => {
                Toast.toast(res.msg.replace('改', '该'))
                if (res.code == 0) {
                    this.getBabyInfo()
                }
                this.setState({
                    admin: {
                        flag: false
                    }
                });
            })
        });
    }

    //基本设备提示操作
    deviceCancel() {
        this.setState({
            admin: {
                flag: true
            }
        });
        let config = {};
        const {
            deviceType
        } = this.state.info;
        if (this.state.info.loststatus == 1) {
            config = {
                tip: '温馨提示',
                newTop: null,
                content: '当前设备已挂失，无法解绑，请先解除挂失！',
                no: '知道了',
                yes: null
            };
        } else {
            if (!this.state.info.isadmin) {
                config = {
                    tip: '温馨提示',
                    newTop: null,
                    content: '确定要解除绑定吗？',
                    yes: '立即解绑'
                };
            } else {
                config = {
                    tip: `是否要解绑${deviceType == 2 ? '学生证' : '考勤卡'}？`,
                    content: `<div class='jiebangbox'><p>解除管理员绑定后，其他监护成员将一同解除，且设备恢复出厂设置，只保留激活状态及设备有效期</p><ul><li>1. 如果是暂时遗失${deviceType == 2 ? '学生证' : '考勤卡'}，请点击 <a onClick="javascript:document.getElementById('guashilink').click()">立即挂失</a> ，找到学生证后解除挂失即可正常使用。</li><li>2. 如果是原设备损坏，购买了新设备，请点击 <a onClick="javascript:document.getElementById('genghuanlink').click()">更换设备</a> ，为宝宝更换设备。请勿解绑原设备，否则原套餐无法在新设备上使用。</li><li>3. 如果想要把当前设备绑定在其他帐号使用，请点击下方立即解绑。</li></ul></div>`,
                    yes: '立即解绑',
                    newTop: '20%'
                };
            }
        }
        this.config = Object.assign({}, this.config, config);
    }
    //删除设备(管理员)
    delDevice2() {
        HttpService.query({
            url: '/app/object/cancelDevice', //'/app/object/cancelBabyWithoutSyn',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10112) {
                    if (localStorage.babylength == 1) {
                        localStorage.babylength = 0;
                        this.context.router.push('/addDevice');
                        return;
                    }
                    localStorage.delDevice = 1;
                    localStorage.is = '0';
                    this.context.router.push('/map/' + localStorage.appToken + '/' + localStorage.userid);
                } else {
                    Toast.toast(res.msg)
                }
                this.setState({
                    admin: {
                        flag: false
                    }
                });
            })
        });
    }

    //删除设备
    delDevice() {
        HttpService.query({
            url: '/app/object/cancelBaby',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },

            success: (res => {
                if (res.code == '10070') {
                    if (localStorage.babylength == 1) {
                        localStorage.babylength = 0;
                        this.context.router.push('/addDevice');
                        return;
                    }
                    localStorage.delDevice = 1;
                    localStorage.is = '0';
                    this.context.router.push('/map/' + localStorage.appToken + '/' + localStorage.userid);
                }
            })
        });
    }
    deviceChange() {
        this.setState({
            admin: {
                flag: true
            }
        });
        if (this.state.info.loststatus == 1) {
            let config = {
                tip: '温馨提示',
                newTop: null,
                content: '当前设备已挂失，无法更换，请先解除挂失！',
                no: '知道了',
                yes: null
            };
            this.config = Object.assign({}, this.config, config);
            return
        }
        if (!this.state.info.isadmin) {
            let config = {
                tip: '温馨提示',
                newTop: null,
                content: `非设备管理员无法更换设备,请联系设备管理员`,
                no: '知道了',
                yes: null
            };
            this.config = Object.assign({}, this.config, config);
            return
        }
        let deviceType = '智能学生证';
        if (this.state.info.deviceType == 3) {
            deviceType = '考勤卡';
        }
        var b = {
            tip: '更换设备',
            content: '当前设备类型为' + deviceType + '，请扫描新的设备二维码或条形码，完成更换！',
            newTop: null,
            type: 'change',
            yes: '去更换'
        };
        this.config = Object.assign({}, this.config, b);
    }

    logOut() {
        localStorage.logout = 1;
        if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
            HttpService.query({
                url: '/app/user/unassociateWithWeChat',
                data: {
                    token: localStorage.appToken,
                    weixinclient: 'true'
                },
                success: (res => {
                    if (res.code == 10211) {
                        this.context.router.push('/');
                    }
                })
            });
        }
        this.context.router.push('/');
    }
    viewCode() {
        console.log('设备二维码');
        _hmt.push(['_trackEvent', 'page', 'more', '设备二维码']);
        this.setState({
            viewCode: 1
        })
    }
    closeCode() {
        this.setState({
            viewCode: 0
        })
    }
    closeTime() {
        this.setState({
            viewtime: 0
        });
        if (localStorage.overtime == undefined)
            localStorage.overtime = ''
        localStorage.overtime = localStorage.overtime + this.props.params.babyid + ',';
    }
    authStatus() {
        const {
            info
        } = this.state;
        if (info.authstatus == 0 || info.authstatus == 2) {
            if (info.tianyin == true) {
                Toast.toast('返回首页下载APP，方可认证');
                return;
            }
            this.context.router.push('/authen/' + info.telephone);
        }
    }

    //我的卡券
    myPackage(e) {
        const jxtBabyId = this.state.info.jxtBabyId
        if (!jxtBabyId) {
            Toast.toast('未获取到学生数据，请联系客服！');
            return
        }
        let url = 'integral.html#/mypackage'
        goJxtFn(url, 3, '&userid=' + jxtBabyId, {
            babyid: this.props.babyid
        });
    };

    render() {
        const {
            info,
            admin,
            uimg,
            utel,
            viewCode,
            viewtime
        } = this.state;
        return (
            <div className="more" style={{
                background: '#eee',
                minHeight: '100%',
                paddingBottom: '4rem'
            }}>

                <Popup config={this.config} blockOrNone={admin.flag} _flag={admin.flag}/>
                <R_header_fixed left="1" title="更多"/> {viewtime == 1
                    ? <div id='overtime'>
                            <div className="model_zindex"></div>
                            <div className="model_content">
                                <div className="header"><img src={header} className="app-all-img"/></div>
                                <div className="content app-padding-lr20">
                                    <div className="_header app-active-font32">过期提醒</div>
                                    <div className="_content step app-666-font24">
                                        <div>您的设备套餐于<span className='colorblue'>{info.endTime}</span>日到期，为了不影响您继续使用，请及时在APP客户端、或微信公众号上缴费。</div>
                                    </div>
                                    <div className="_footer step">
                                        <div className="s-center app-active-font32" onClick={this.closeTime.bind(this)} style={{
                                            color: '#666'
                                        }}>我知道了</div>
                                    <Link className="s-center app-active-font32" to={'/pay/' + info.babyid + '/' + info.deviceid}>缴费</Link>
                                    </div>
                                </div>
                                <div className="footer"><img src={footer} className="app-all-img"/></div>
                            </div>
                        </div>
                    : ''}
                <div className="more-content">
                    <img src={info.url} style={{
                        display: 'none'
                    }}/> {viewCode == 1
                        ? <div id='viewCode'>
                                <div className="barcode">
                                    <img src={info.url}/>
                                    <div className="mdtid" style={{
                                        color: '#666'
                                    }}>扫描二维码关注宝贝的设备</div>
                                    <div className="mdtid">设备IMEI号:{info.mdtid}</div>
                                    <div className='closecode' onClick={this.closeCode.bind(this)}>确定</div>
                                </div>
                            </div>
                        : ''
                    }


                    <div className='moreuserinfo'>
                        <div className='imgbox' onClick={this.updateUser.bind(this)}><img src={uimg+'s'} onError={imgOnError.bind(this,defaultHeadImg)}/></div>
                        <p>{utel}</p>
                    </div>
                    {info.deviceType == '2' && info.isadmin
                        ? <div authstatus={info.authstatus} onClick={this.authStatus.bind(this)}>
                                <div className="shiming">
                                    <div className="img">
                                        <img src={shiming}/>
                                    </div>
                                    <div className="input">sim卡实名认证</div>
                                    <div className="select">
                                        {info.authstatus == '0'
                                            ? <div className="step">
                                                    <span style={{
                                                        color: '#999999'
                                                    }} className="step"><img src={unauthen} className="authImg"/>
                                                        未认证
                                                    </span>
                                                    <span><img src={j} className="jimg"/></span>
                                                </div>
                                            : info.authstatus == '1'
                                                ? <span style={{
                                                        color: '#f7ba00'
                                                    }}>
                                                        认证中</span>
                                                : info.authstatus == '2'
                                                    ? <div className="step">
                                                            <span className="step" style={{
                                                                color: '#ff6e6e'
                                                            }}>
                                                                认证不通过</span>
                                                            <span>
                                                                <img src={j} className="jimg"/></span>
                                                        </div>
                                                    : info.authstatus == '3'
                                                        ? <span style={{
                                                                color: '#1ec94a'
                                                            }}><img src={authen} className="authImg"/>
                                                                已认证</span>
                                                        : ''
}

                                    </div>
                                </div>
                            </div>
                        : ''
}
                    {info.deviceType == 3
                        ? <div onClick={this.shengJi}>
                                <Link className="endtime" to='/shengji/more'>
                                    <div className="img">
                                        <img src={imgSheng}/> {localStorage.shengji
                                            ? ''
                                            : <div className='newfn'></div>}
                                    </div>
                                    <div className="input">升级设备</div>
                                    <div className="select">
                                        <span style={{
                                            color: '#f7ba00'
                                        }}>增加安全保障</span>

                                        <span className="step"><img src={j} className="jimg"/></span>
                                    </div>
                                </Link>
                            </div>
                        : ''
}

                    <Link className="endtime tgMoreButtonList buydevicelink" to={'/baby/' + info.babyid}>
                        <div className="img">
                            <img src={imgBaby}/>
                        </div>
                        <div className="input">宝贝信息</div>
                        <div className="select">
                            <span className="step"><img src={j} className="jimg"/></span>
                        </div>
                    </Link>
                    <div className="endtime tgMoreButtonList buydevicelink" onClick={this.myPackage.bind(this)}>
                        <div className="img">
                            <img src={imgpackage}/>
                        </div>
                        <div className="input">我的卡券</div>
                        <div className="select">
                            <span className="step"><img src={j} className="jimg"/></span>
                        </div>
                    </div>
                    <div className='morelinkbox'>
                        <div className='titlebar'>设备信息</div>
                        <div className='clearfix lists'>
                            {info.deviceid?
                            <div className="fnitem percent2">
                                <div className="img">
                                    <img src={imgphone}/>
                                </div>
                                <div className="lkname">
                                    <p>设备手机号</p>
                                    <p className='detail'>
                                        {info.deviceType == 3
                                            ? '当前设备不支持'
                                            : info.telephone}
                                    </p>
                                </div>
                            </div>:null}
                            {info.deviceid?
                            <div className="fnitem percent2" onClick={this.viewCode.bind(this)}>
                                <div className="img">
                                    <img src={imgcode}/>
                                </div>
                                <div className="lkname">设备二维码</div>
                            </div>:null}
                            <div className="fnitem percent2">
                                <div className="img">
                                    <img src={imgtime}/>
                                </div>
                                <div className="lkname">
                                    <p>设备有效期</p>
                                    <p className='detail'>{info.endTime}</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className='morelinkbox'>
                        <div className='titlebar'>设备功能</div>
                        <div className='clearfix lists'>
                            <Link className="fnitem percent4" to={'/Guardian/' + info.babyid+'/'+info.deviceType+'/'+info.deviceid}>
                                <div className="img">
                                    <img src={imgusers}/>
                                </div>
                                <div className="lkname">成员管理</div>
                            </Link>
                            {info.deviceType==2?<Link className="fnitem percent4" to={'/Safetyarea/' + info.babyid}>
                                <div className="img">
                                    <img src={imganquan}/>
                                </div>
                                <div className="lkname">安全区域</div>
                            </Link>:null}
                        </div>
                    </div>
                    <div className='morelinkbox'>
                        <div className='titlebar'>设备管理</div>
                        <div className='clearfix lists'>
                            <Link className="fnitem percent4 adddevicelink" to='/addDevice'>
                                <div className="img">
                                    <img src={imgadd}/>
                                </div>
                                <div className="lkname">添加设备</div>
                            </Link>
                            {info.deviceType == 2 && info.deviceid&&info.loststatus!=1
                                ? <Link className="fnitem percent4 tgPayMoney" to={'/pay/' + info.babyid + '/' + info.deviceid}>
                                        <div className="img">
                                            <img src={pay}/>
                                        </div>
                                        <div className="lkname">续费</div>
                                    </Link>
                                : null}
                            {info.deviceid?
                            <div className="fnitem percent4" onClick={this.deviceChange.bind(this)} id='genghuanlink'>
                                    <div className="img">
                                        <img src={imgchange}/>
                                    </div>
                                    <div className="lkname">更换设备</div>
                                </div>
                            : null}
                            <Link className="fnitem percent4 buydevicelink" to='/BuyDevice'>
                                <div className="img">
                                    <img src={imgCard}/>
                                </div>
                                <div className="lkname">购买新设备</div>
                            </Link>
                            {info.deviceid?<div className="fnitem percent4" onClick={this.deviceCancel.bind(this)}>
                                <div className="img">
                                    <img src={imgjiebang}/>
                                </div>
                                <div className="lkname">解绑设备</div>
                            </div>:
                            <div className="fnitem percent4"  onClick={this.deviceAdd.bind(this)}>
                                <div className="img">
                                    <img src={bangding}/>
                                </div>
                                <div className="lkname">绑定设备</div>
                            </div>}
                            {info.deviceid?
                            <div className="fnitem percent4" onClick={this.deviceGuaShiTip.bind(this)} id='guashilink'>
                                <div className="img">
                                    <img src={info.loststatus==1?imgguashi2:imgguashi}/>
                                </div>
                                <div className="lkname">{info.loststatus==1?'解除挂失':'设备挂失'}</div>
                            </div>:null}
                        </div>
                    </div>
                    <div className="step app-logout tgMoreButtonList" data-tgOptValue="退出登录" onClick={this.logOut.bind(this)}>
                        <div className="s-center" style={{
                            padding: '.33rem',
                            fontSize: '1.4rem',
                            letterSpacing: '4px'
                        }}>
                            退出登录
                        </div>
                    </div>
                </div>

            </div>
        )
    }

}

More.contextTypes = {
    router: React.PropTypes.object.isRequired
};
